<script setup lang="ts">
import {ref} from "vue";
import {
  ExportProjectExcel, getTeacherType,
  projectAdds,
  projectAll, projectBatchAdds,
  projectDelects, projectEdits,
  projectPage
} from "@/pages/project/projectManagement/index.js";
import TableTemplate from "@/pages/account/components/tableTemplate.vue";
import {ElMessage} from "element-plus";
import BatchAddTemplate from "@/pages/account/components/batchAddTemplate.vue";
import DialogTemplate from "@/pages/account/components/dialogTemplate.vue";
import {
  addProjectFunding,
  addProjectProgress,
   editProjectFunding, getProjectFundingDetailId,
  getProjectProgressList
} from "@/pages/account/accountApi.js";
import {useUserStore} from "@/pinia/stores/user";
import { ElNotification } from 'element-plus'
const userStore = useUserStore()
const userData = userStore.userInfo
const registerDialogRef = ref(null)
const type = ref([])
const teacherType = ref([])
import { useRouter } from 'vue-router';
const router = useRouter();
// 刷新loading
const loading = ref(false)
const statues = [
  {
    value: 0,
    label: '待审核',
  }, {
    value: 1,
    label: '审核中',
  },
  {
    value: 2,
    label: '审核通过',
  }, {
    value: 3,
    label: '审核不通过',
  },
  {
    value: 4,
    label: '驳回',
  }
]
// websocket连接对象
const ws = ref(null)
//表格引用
const registerTableRef = ref(null)
// 弹窗引用
const dialogTemplateRef = ref(null)
// 弹窗引用
const dialogTemplateVisible = ref(false)
const centerDialogVisible = ref(false)
const fundingDialogVisible = ref(false)
// 弹窗标题引用
const title = ref('')
// 弹窗表单数据
const initialData = ref({})
let formItems = ref([{
  list: [
    {
      label: '项目名称',
      prop: 'title',
      type: 'input',
      rules: [
        {required: true, message: '请输入项目名称', trigger: 'blur'},
        {min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur'}
      ],
      placeholder: '请输入项目名称'
    },
    {
      label: '项目负责人',
      prop: 'username',
      type: 'input',
      rules: [
        {required: true, message: '请输入项目负责人', trigger: 'blur'},
        {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
      ],
      placeholder: '请输入项目负责人'
    },
    {
      label: '项目成员',
      prop: 'menber',
      type: 'input',
      rules: [
        {required: true, message: '请输入其他项目成员,多个以英文逗号分隔', trigger: 'blur'},
        {min: 2, max: 40, message: '长度在 2 到 40 个字符', trigger: 'blur'}
      ],
      placeholder: '请输入其他项目成员'
    },
    {
      label: '项目介绍',
      prop: 'content',
      type: 'richText',
      rules: [
        {required: true, message: '请输入项目介绍', trigger: 'blur'},
        {min: 20, max: 1500, message: '长度在 20 到 1500 个字符', trigger: 'blur'}
      ],
      placeholder: '请输入项目介绍'
    },
    {
      label: '项目类型',
      prop: 'protype',
      type: 'select',
      options: type.value,
      placeholder: '请选择项目类型'
    },
    {
      label: '指导老师',
      prop: 'instructor',
      type: 'select',
      options: teacherType.value,
      placeholder: '请选择指导老师'
    },
    {
      label: "是否支持下载",
      prop: "download",
      type: "switch",
      value: 0,
    },
    {
      label: '项目图片',
      prop: 'projectImg',
      type: 'uploadImage',
      multiple: true,
      limit: 1,
      rules: [
        {required: true, message: '请上传项目图片', trigger: 'blur'}
      ],
      placeholder: '请上传项目图片'
    },
    {
      label: '项目附件',
      prop: 'file',
      type: 'uploadFile',
      multiple: true,
      limit: 1,
      rules: [
        {required: true, message: '请上传项目附件', trigger: 'blur'}
      ],
      placeholder: '请上传项目附件'
    }
  ]
}])
// 是否查看模式
const isViewMode = ref(false)
// 弹窗提交的数据
const formData = ref({})
// 操作名称
const operationName = ref('')
//选中的行
const handleIndex = ref([])
const handleChange = (data) => {
  handleIndex.value = data
}
//批量新增弹窗引用
let batchAddVisible = reactive({
  fileName: '项目批量新增模板.xlsx',
  dialogFormVisibles: false,
})
//项目状态
const getStatusColor = (statuss) => {
  switch (statuss) {
    case '待审核':
      return 'primary';
    case '审核中':
      return 'success';
    case '审核通过':
      return 'danger';
    case '审核不通过':
      return 'warning';
    default:
      return 'info';
  }
};
// 提交状态
const getSubmitColor = (data) => {
  switch (data) {
    case 0:
      return 'primary';
    default:
      return 'success';
  }
}
// 提交状态
const getStatusText = (data) => {
  switch (data.isSubmit) {
    case 0:
      return '待提交';
    default:
      return '已提交';
  }
}
const projectTypeAll = async () => {
  //获取项目类型
  let data = await projectAll()
  for (let i = 0; i < data.data.length; i++) {
    type.value.push({
      label: data.data[i].projectType,
      value: data.data[i].id
    });
  }
}
const teacherTypeAll = async () => {
  //教师名称
  let data = await getTeacherType()
  for (let i = 0; i < data.data.length; i++) {
    teacherType.value.push({
      label: data.data[i].username,
      value: data.data[i].id
    });
  }
}

let dataSet = reactive({
  queryBox: [
    {
      model: 'title',
      type: 'input',
      placeholder: '请输入项目名称'
    },
    {
      model: 'username',
      type: 'input',
      placeholder: '项目发起人'
    },
    {
      model: 'type',
      type: 'select',
      placeholder: '项目类型',
      options: type.value,
    },
    {
      model: 'status',
      type: 'select',
      placeholder: '项目状态',
      options: statues,
    }
  ],
  tableList: [
    {prop: 'title', label: '项目名称', width: '180'},
    {prop: 'username', label: '项目发起人', width: '100'},
    {prop: 'protype', label: '项目类型', width: '150'},
    {prop: 'menber', label: '项目成员', width: '180'},
    {prop: 'createTime', label: '创建时间', width: '180'},
    {prop: 'instructor', label: '指导老师', width: '180'}
  ],
  tnQueryTop: [
    {name: '新增', click: 'projectAdd', type: 'primary'},
    {name: '批量新增', click: 'projectBatchAdd', type: 'primary'},
    {name: '批量删除', click: 'projectBatchDelete', type: 'danger'},
    {name: '导出', click: 'exportProjectExcel', type: 'primary'},
  ],
  tableListStutas: [
    {prop: 'statuss', label: '项目状态', width: '100', stutasColor: 'danger'},
  ],
  tableListSubmit: [
    {prop: 'isSubmit', label: '提交状态', width: '100', stutasColor: 'danger'},
  ],
  operationBtns: [
    {name: '编辑', click: 'projectEdit', type: 'primary',role:true},
    {name: '详情', click: 'projectDetail', type: 'info'},
    {name: '提交审核', click: 'submitAudit', type: 'warning',role:true},
    {name: '审核日志', click: 'examineLog', type: 'success'},
    {name: '资金申请', click: 'projectFunding', type: 'success',role:true},
    {name: '删除', click: 'deleteId', type: 'danger',role:true},
  ],

  tableData: {
    total: 0,
    rows: []
  }
})
//查询条件
const selectSubmit = async (data) => {
  loading.value = true
  if (userData.occupation==0){
    data.userId=userData.id;
  } else if(userData.occupation==1){
    data.teacherId=userData.id;
  }
  await projectPage(data, data.pageSize, data.pageNum).then(rows=>{
    dataSet.tableData.rows = rows.data.records;
    dataSet.tableData.total = rows.data.total;
  }).finally(() => {
    loading.value = false
  });
}
// 重置
const resetSubmit = (data) => {
  selectSubmit(data);
}

onMounted(() => {
  selectSubmit({});
  projectTypeAll();
  teacherTypeAll();
})
// 批量新增
const projectBatchAdd = () => {
  batchAddVisible.dialogFormVisibles = true
}
//projectBatchAdd提交
const batchAddSubmit = async (fileList, username) => {
  // 必须包含的字段
  const requiredFields = ["项目名称", "项目负责人", "项目成员", "项目类型", "是否支持下载"];

  // 检查 fileList 的字段
  const isValidFile = fileList.every(item =>
    requiredFields.every(field => Object.prototype.hasOwnProperty.call(item, field))
  );

  if (!isValidFile) {
    ElMessage.error("文件格式错误，请上传正确的模板文件！");
    return;
  }

  // 构造数据
  const data = fileList.map(item => ({
    title: item.项目名称,
    username: item.项目负责人,
    menber: item.项目成员,
    content: item.项目介绍,
    instructor: item.指导老师,
    teacherId: getTeacherName(item.指导老师),
    type: getProjectType(item.项目类型),
    download: item.是否支持下载-1,
    userId: userData.id,
    status: 0,
    isSubmit: 0
  }));

  if (data.length < 1) {
    ElMessage.error("文件内容为空，请检查模板文件！");
    return;
  }
  //批量新增
  let response = await projectBatchAdds(data);
  if (response.code === 0) {
    ElMessage.success("批量新增成功");
    batchAddVisible.dialogFormVisibles = false;
    selectSubmit({});
    return;
  }
  ElMessage.error(response.message || "批量新增失败，请检查表单");
};
const getProjectType = (data) => {
  const foundType = type.value.find(item => item.label === data);
  return foundType ? foundType.value : undefined;
}


// 批量删除
const projectBatchDelete = () => {
  if (handleIndex.value.length === 0) {
    ElMessage.error('请至少选择一条数据！')
    return;
  }
  ElMessageBox.confirm(
    '确定要删除这些项目吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    //ids列表

    const ids = handleIndex.value.map(item => item.id)
    await projectDelects(ids).then(response => {
      if (response.code === 0) {
        ElMessage.success('删除成功')
        registerTableRef.value?.clearSelection();
        selectSubmit({});
      } else {
        ElMessage.error('删除失败')
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除',
    })
  })
}
// 导出
const exportProjectExcel = () => {
  if (handleIndex.value.length < 1) {
    ElMessage.error("请选择要导出的数据！")
    return
  }
  ExportProjectExcel(handleIndex.value)
  ElMessage.success('导出成功')
}
// 新增
const projectAdd = () => {
  operationName.value = '新增'
  title.value = '新增项目'
  isViewMode.value = false
  initialData.value = {}
  dialogTemplateVisible.value = true
  dialogTemplateRef.value.dialogTemplateVisible = true;
}
// 编辑
const projectEdit = (data) => {
  operationName.value = '编辑'
  title.value = '编辑项目'
  isViewMode.value = false
  initialData.value = {...data}
  dialogTemplateVisible.value = true
  dialogTemplateRef.value.dialogTemplateVisible = true;
}
// 详情
const projectDetail = (data) => {
  operationName.value = "详情"
  title.value = '项目详情'
  isViewMode.value = true
  initialData.value = {...data}
  dialogTemplateVisible.value = true
  dialogTemplateRef.value.dialogTemplateVisible = true;
}
// 删除
const deleteId = async (data) => {
  let response = await projectDelects([data.id])
  if (response.code === 0) {
    ElMessage.success('删除成功')
    registerTableRef.value?.clearSelection();
    selectSubmit({});
  } else {
    ElMessage.error('删除失败')
  }
}
// 提交审核
const submitAudit = async (data) => {
  if (data.isSubmit === 1 && (data.status === 0 || data.status === 1)) {
    ElMessage.error('该项目已提交审核，请勿重复提交')
    return;
  }
  ElMessageBox.confirm(
    '确定要提交审核吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    data.isSubmit = 1
    if (data.status === 2 || data.status === 3){
      data.status=0;
    }
    let response = await projectEdits({...data})
    await addProjectProgress({projectId: data.id, role: "学生"})
    if (response.code === 0) {
      ElMessage.success('提交审核成功')
      registerTableRef.value?.clearSelection();
      selectSubmit({});
      ws.value.send(JSON.stringify({projectName: data.title, person: data.username, projectId: data.id,
        userId: data.userId, teacherId: data.teacherId})); // 发送消息
    } else {
      ElMessage.error(response.message || "提交审核失败");
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消提交',
    })
  })
}

// 连接ws
const ljie = () => {
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    return;
  }
  ws.value = new WebSocket(`ws://localhost:8082/progress/review/${userData.id}`);
  ws.value.onopen = (event) => {

  };
  ws.value.onerror = (error) => {

  };
  ws.value.onclose = (event) => {

  };
  ws.value.onmessage = (event) => {
    try {
      const message = JSON.parse(event.data);
      openAudit(message);
    } catch (error) {

    }
  };
}
ljie();
// 当有审核消息时，弹窗显示消息
const openAudit = (data) => {
  ElNotification({
    title: data.title,
    dangerouslyUseHTMLString: true,
    message: data.description+' 点击前往查看',
    type: 'success',
    onClick: () => {
      if (data.userId){
        router.push({path: '/projectAccount/examine'})
      }
    }
  })
}

const getTeacherName = (name) => {
  const teacher = teacherType.value.find(item => item.label === name);
  return teacher ? teacher.value : undefined;
}
const getTeacherNameById = (id) => {
  const teacher = teacherType.value.find(item => item.value === id);
  return teacher ? teacher.label : undefined;
}
// 审核日志
const activities = ref([])
const activitiesProgress = ref([])
// 审核日志
const examineLog = async (data) => {
  if (data.isSubmit ===0 && data.status === 0) {
    ElMessage.error('该项目未提交审核，请先提交审核')
    return;
  }
  let rows = await getProjectProgressList(data.id);
  activities.value = rows.data.progressList;
  activitiesProgress.value = rows.data.reviewList;
  centerDialogVisible.value = true
}
const ruleFormRef = ref(null)
// 资金申请
const projectForm = ref({})
//审核弹窗便签
const activeName = ref('first')
const fundingAactive = ref('first')
const fundingForm = ref({
  projectId: '',
  projectName: '',
  projectType: '',
  userId: '',
  username: '',
  reviewerId: userData.id,
  reviewer: userData.username,
  instructor: '',
  funding: '',
  equipment: '',
  equipmentMoney: '',
  materialCost: '',
  materialMoney: '',
  otherCost: '',
  otherMoney: '',
})
const projectFunding = async (data) => {
  if (data.isSubmit === 0) {
    ElMessage.error('该项目未提交，请先提交审核')
    return
  }
 let response = await getProjectProgressList(data.id);
  if (response.data.reviewList === null || response.data.reviewList.active !== 3) {
    if (response.data.reviewList.active === 2){
      ElMessage.error('管理员未审核或不通过！')
      return;
    }
    if (response.data.reviewList.active === 1){
      ElMessage.error('您的指导老师未审核或不通过，请耐心等待！')
      return;
    }
    ElMessage.error('该项目未通过审核，请先通过审核')
    return;
  }
  projectForm.value = {...data}
  operationName.value = '申请'
  title.value = '资金编辑'
  // 查询该项目是否有资金申请
  await getProjectFundingDetailId(data.id).then(response => {
    if (response.data !== null) {
      fundingForm.value= response.data;
      operationName.value = '查看'
    }else {
      title.value = '资金申请'
      fundingForm.value.projectId = data.id;
      fundingForm.value.projectName = data.title;
      fundingForm.value.userId = data.userId;
      fundingForm.value.username = data.username;
      fundingForm.value.projectType = data.protype;
      fundingForm.value.instructor = data.instructor || '';
    }
  });
  isViewMode.value = false
  // 确保项目数据加载后，将对应的数据赋值给 fundingForm
  fundingDialogVisible.value = true
}

const submitFundingForm = async () => {
  if (fundingForm.value.funding === '' || fundingForm.value.equipment === ''
    || fundingForm.value.equipmentMoney === '' ||
    fundingForm.value.materialCost === '' ||
    fundingForm.value.materialMoney === '' )
    {
      ElMessage.error('请填写完整信息')
      return;
    }
  if (title.value === '资金编辑'){
    await editProjectFunding({...fundingForm.value}).then(response => {
      if (response.code === 0) {
        ElMessage.success('资金编辑成功')
        fundingDialogVisible.value = false
      }
    })
    return;
  }
    await addProjectFunding({...fundingForm.value}).then(response => {
      if (response.code === 0) {
        ElMessage.success('资金申请成功')
        fundingDialogVisible.value = false
      }
    })
}
const handleDialogSubmit = async (data) => {
  formData.value = data;
  if (!Number.isInteger(data.protype)) {
    data.type = getProjectType(data.protype);
  }else {
    data.type = data.protype;
  }
  let response;
  if (operationName.value === "新增") {
    data.userId = userData.id
    data.teacherId = data.instructor
    data.instructor = getTeacherNameById(data.instructor);
    response = await projectAdds(data);
    if (response.code === 0) {
      ElMessage.success("新增成功");
      dialogTemplateVisible.value = false
    } else {
      ElMessage.error(response.message || "新增失败，请检查表单");
    }
  } else if (operationName.value === "编辑") {
    response = await projectEdits(data);
    if (response.code === 0) {
      ElMessage.success("编辑成功");
      dialogTemplateVisible.value = false
    } else {
      ElMessage.error(response.message || "编辑失败，请检查表单");
    }
  } else if (operationName.value === "删除") {
    response = await projectDelects(data);
    if (response.code === 0) {
      ElMessage.success("删除成功");
      dialogTemplateVisible.value = false
    }
  }
  selectSubmit({});
}
</script>
<template>
  <div>
    <TableTemplate
      ref="registerTableRef"
      :data-set="dataSet"
      @deleteId="deleteId"
      @projectAdd="projectAdd"
      @projectBatchAdd="projectBatchAdd"
      @examineLog="examineLog"
      @projectFunding="projectFunding"
      @projectBatchDelete="projectBatchDelete"
      @exportProjectExcel="exportProjectExcel"
      @projectEdit="projectEdit"
      @projectDetail="projectDetail"
      @reset-submit="resetSubmit"
      @submitAudit="submitAudit"
      @handleChange="handleChange"
      @select-submit="selectSubmit"
      :get-status-color="getStatusColor"
      :get-submit-color="getSubmitColor"
      :get-status-text="getStatusText"
      :loading="loading"
    />
    <BatchAddTemplate
      ref="registerDialogRef"
      v-model="batchAddVisible.dialogFormVisibles"
      @submit-adds="batchAddSubmit"
      @projectBatchAdd="projectBatchAdd"
      :batch-add-visible="batchAddVisible"
    />
    <DialogTemplate
      v-model="dialogTemplateVisible"
      ref="dialogTemplateRef"
      :title="title"
      :width="'800px'"
      :initial-data="initialData"
      :form-items="formItems"
      :is-view="isViewMode"
      @handleDialogSubmit="handleDialogSubmit"
      :operation-name="operationName"
    />
    <el-dialog v-model="centerDialogVisible" title="审核日志" width="700">
      <div>
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="审核进度" name="first">
            <el-timeline style="max-width: 600px;margin-left: 20px;margin-top: 10px">
              <el-timeline-item
                v-for="(activity, index) in activities"
                :key="index"
                placement="top"
                :timestamp="activity.role!=='学生'?activity.role+'  审核':activity.role+'  提交'"
              ><el-card>
                <span>{{ activity.auditTime }}</span>
                <br>
                <span class="span-text" v-if="activity.role!== '学生'">审核结果：{{
                    activity.auditResult === 0 ? '通过' : activity.auditResult === 1 ? '不通过' : '驳回'
                  }}</span>
                <br v-if="activity.role !== '学生'">
                <span class="span-text" v-if="activity.role !== '学生'">审核意见：  {{ activity.reviewComments }}</span>
              </el-card>
              </el-timeline-item>
            </el-timeline>
          </el-tab-pane>
          <el-tab-pane label="审核步骤" name="second">
            <el-steps style="max-width: 600px" finish-status="success" :active="activitiesProgress.active">
              <el-step title="学生提交审核" :description="activitiesProgress.sTime"/>
              <el-step title="教师审核" :description="activitiesProgress.tTime"/>
              <el-step title="管理员审核" :description="activitiesProgress.aTime"/>
            </el-steps>
          </el-tab-pane>
        </el-tabs>
      </div>
      <template #footer>
        <div class="dialog-footer" style="margin-top: 10px">
          <el-button @click="centerDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="fundingDialogVisible" :title="title" width="700">
      <el-tabs v-model="fundingAactive" class="demo-tabs">
        <el-tab-pane label="项目详情" name="first">
          <el-form
            ref="ruleFormRef"
            style="max-width: 600px"
            :model="projectForm"
            status-icon
            label-width="auto"
          >
            <el-form-item label="项目名称" prop="title">
              <el-input :disabled="true" v-model="projectForm.title" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="项目负责人" prop="username">
              <el-input :disabled="true" v-model="projectForm.username"/>
            </el-form-item>
            <el-form-item label="项目成员" prop="menber">
              <el-input :disabled="true" v-model="projectForm.menber"/>
            </el-form-item>
            <el-form-item label="项目类型" prop="protype">
              <el-input :disabled="true" v-model="projectForm.protype"/>
            </el-form-item>
            <el-form-item label="指导老师" prop="instructor">
              <el-input :disabled="true" v-model="projectForm.instructor"/>
            </el-form-item>
            <el-form-item label="项目简介" prop="instructor">
              <el-input :disabled="true" v-model="projectForm.content"/>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane :label="title" name="second">
          <el-form ref="ruleFormRef" style="max-width: 600px" :model="fundingForm" status-icon label-width="auto">
            <el-form-item label="申请金额" prop="funding">
              <el-input style="width: 30%" v-model.number="fundingForm.funding" placeholder="请输入申请金额"/>
              &nbsp;&nbsp;万元
            </el-form-item>
            <el-form-item label="设备采购" prop="equipment" style="flex: 1; margin-right: 10px;">
              <el-input v-model="fundingForm.equipment" type="textarea" autosize placeholder="请输入设备采购名称"/>
            </el-form-item>
            <el-form-item label="设备金额" prop="equipmentMoney" style="flex: 1;">
              <el-input v-model.number="fundingForm.equipmentMoney" style="width: 30%;" placeholder="请输入设备金额"/>
              &nbsp;&nbsp;万元
            </el-form-item>
            <el-form-item label="材料采购" prop="materialCost" style="flex: 1; margin-right: 10px;">
              <el-input v-model="fundingForm.materialCost" type="textarea" autosize placeholder="请输入材料采购名称"/>
            </el-form-item>
            <el-form-item label="材料金额" prop="materialMoney" style="flex: 1;">
              <el-input v-model.number="fundingForm.materialMoney"  style="width: 30%;" placeholder="请输入材料金额"/>
              &nbsp;&nbsp;万元
            </el-form-item>
            <el-form-item label="其他内容" prop="otherCost" style="flex: 1; margin-right: 10px;">
              <el-input v-model="fundingForm.otherCost" type="textarea" autosize placeholder="请输入其他详细信息"/>
            </el-form-item>
            <el-form-item label="其他费用" prop="otherMoney" style="flex: 1;">
              <el-input v-model.number="fundingForm.otherMoney" style="width: 30%;" placeholder="请输入其他费用金额"/>
              &nbsp;&nbsp;万元
            </el-form-item>
            <div style="margin-left: 45%; margin-top: 10px;">
              <el-button type="primary" @click="submitFundingForm">提交</el-button>
              <el-button @click="fundingDialogVisible = false">取消</el-button>
            </div>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">

</style>
